package com.bsoft.gol.hbs.dao;

import ctd.persistence.annotation.DAOMethod;
import ctd.persistence.annotation.DAOParam;
import ctd.persistence.support.hibernate.HibernateSupportDelegateDAO;
import ctd.persistence.support.hibernate.template.AbstractHibernateStatelessResultAction;
import ctd.persistence.support.hibernate.template.HibernateSessionTemplate;
import ctd.persistence.support.hibernate.template.HibernateStatelessResultAction;
import org.hibernate.Query;
import org.hibernate.StatelessSession;
import pcn.bean.hpi.PcnHpiResident;
import pcn.enums.ViewStatus;
import pcn.sign.PcnPeopleMould;

import java.util.List;

public abstract class PcnHpiResidentDAO extends HibernateSupportDelegateDAO<PcnHpiResident> {
	public PcnHpiResidentDAO() {
		this.setKeyField("id");
	}

	@DAOMethod(sql = "from PcnHpiResident where mpiId=:mpiId and hpiId=:hpiId")
	public abstract List<PcnHpiResident> findPcnHpiResidentsByMpiIdAndHpiId(@DAOParam("mpiId") String mpiId, @DAOParam("hpiId") int hpiId);

	@DAOMethod(sql = "from PcnHpiResident where mpiId=:mpiId")
	public abstract List<PcnHpiResident> findPcnHpiResidentsByMpiId(@DAOParam("mpiId") String mpiId);

	public  List<PcnHpiResident> findPcnHpiResidentsByMpiIdAndStatus(final String mpiId){
		//@DAOMethod(sql = "")
		HibernateStatelessResultAction<List<PcnHpiResident>> action = new AbstractHibernateStatelessResultAction<List<PcnHpiResident>>() {
			@Override
			public void execute(StatelessSession ss) throws Exception {
				String sql = "from PcnHpiResident where mpiId=:mpiId and  hpiId in(select b.hpiId from PcnBaseHpi b  where b.status=:status and b.typeId in(select t.typeId from PcnHpiType t where t.status=:status))";
				Query query = ss.createQuery(sql.toString());
				query.setString("mpiId",mpiId);
				query.setString("status", ViewStatus.enable.getValue());
				setResult((List<PcnHpiResident>)query.list());
			}
		};
		HibernateSessionTemplate.instance().execute(action);
		return action.getResult();
	}

	
	public void updatePcnHpiResident(final PcnHpiResident pcnHpiResident) {
		HibernateStatelessResultAction<List<PcnPeopleMould>> action = new AbstractHibernateStatelessResultAction<List<PcnPeopleMould>>() {
			@Override
			public void execute(StatelessSession ss) throws Exception {
				String sql = "update PcnHpiResident set hpiCode=? ,lowerLimit=?,upperLimit=?,lastModifyUser=?,lastModifyDt=? where hpiId=? and mpiId=?";
				Query query = ss.createQuery(sql.toString());
				query.setString(0, pcnHpiResident.getHpiCode()).setString(1, pcnHpiResident.getLowerLimit()).setString(2, pcnHpiResident.getUpperLimit()).setString(3, pcnHpiResident.getLastModifyUser()).setDate(4, pcnHpiResident.getLastModifyDt()).setInteger(5, pcnHpiResident.getHpiId()).setString(6, pcnHpiResident.getMpiId());
				query.executeUpdate();
			}
		};
		HibernateSessionTemplate.instance().execute(action);
	}

}
